package com.bw.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.bw.entity.AssetInfo;
import com.bw.entity.Dict;
import com.bw.mapper.AssetInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AssetInfoServiceImpl implements AssetInfoService{


    @Autowired
    AssetInfoMapper assetInfoMapper;

    @Transactional
    @Override
    public AssetInfo addAssetInfo(AssetInfo assetInfo) {

        //表单非空校验，“*”非空字段

//        if (assetInfo.getSourceId() == null){
//            throw new RuntimeException("资产类别不为空"); // 程序会停到这里，抛出异常，程序结束
//        }

        // hutool工具类  断言工具类（判定，断定的意思）
        Assert.notNull(assetInfo.getTypeId(),"资产类别不为空");
        Assert.notBlank(assetInfo.getName(),"资产名称不为空");
        Assert.notNull(assetInfo.getSourceId(),"资产来源不为空");
        Assert.notBlank(assetInfo.getCreateTime(),"购入日期不为空");
        Assert.notBlank(assetInfo.getPrice(),"购入价格不为空");

        //资产编号唯一性校验（不能重复）

        AssetInfo assetInfoDB =  assetInfoMapper.getAssetInfoByNum(assetInfo.getNum());
        if (assetInfoDB != null){
            throw new RuntimeException("资产编号不能重复");
        }
//        Assert.isNull(assetInfoDB,"资产编号不能重复");

        // 购入价格校验，必须为数值类型

        boolean number = NumberUtil.isNumber(assetInfo.getPrice());
        if (!number){
            throw new RuntimeException("购入价格必须为数值类型");
        }
        //控制打印方法参数
        System.out.println("方法的参数是 " + JSON.toJSONString(assetInfo));

        //添加成功
        assetInfoMapper.addAssetInfo(assetInfo);
        //返回资产对象
        return assetInfo;
    }

    @Override
    public AssetInfo selectAssetInfo(String num) {

        AssetInfo assetInfoDB =  assetInfoMapper.getAssetInfoByNum(num);
        // 查询下拉框的数据
         List<Dict>  typeList = assetInfoMapper.listType();
         assetInfoDB.setTypeList(typeList);
         List<Dict>  sourceList = assetInfoMapper.listSource();
         assetInfoDB.setSourceList(sourceList);
        return assetInfoDB;
    }
}
